﻿import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../core/models/heart_rate_api_data.dart';
import '../../../widgets/fixed_header_with_tabs.dart';
import 'dart:ui' as ui;
import 'heart_rate_variability_logic.dart';

/// 心率变异性图表绘制器
class HrvChartPainter extends CustomPainter {
  final List<int> data;
  final int selectedIndex;
  final double? dragLineX;
  final int maxValue;
  final int minValue;

  HrvChartPainter({
    required this.data,
    required this.selectedIndex,
    this.dragLineX,
    required this.maxValue,
    required this.minValue,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (data.isEmpty) return;

    final paint = Paint()
      ..color = const Color(0xFFFFD700)
      ..strokeWidth = 2.0
      ..style = PaintingStyle.stroke;

    final pointPaint = Paint()
      ..color = const Color(0xFFFFD700)
      ..style = PaintingStyle.fill;

    final selectedPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    final path = Path();
    final pointWidth = size.width / data.length;
    final range = maxValue - minValue;
    final scaleY = size.height / range;

    for (int i = 0; i < data.length; i++) {
      final x = i * pointWidth + pointWidth / 2;
      final y = size.height - (data[i] - minValue) * scaleY;

      if (i == 0) {
        path.moveTo(x, y);
      } else {
        path.lineTo(x, y);
      }

      // 绘制数据点
      if (i == selectedIndex) {
        canvas.drawCircle(Offset(x, y), 4, selectedPaint);
      } else {
        canvas.drawCircle(Offset(x, y), 3, pointPaint);
      }
    }

    canvas.drawPath(path, paint);

    // 绘制拖动线
    if (dragLineX != null && dragLineX! > 0) {
      final linePaint = Paint()
        ..color = Colors.red.withOpacity(0.5)
        ..strokeWidth = 1.0;
      canvas.drawLine(
        Offset(dragLineX!, 0),
        Offset(dragLineX!, size.height),
        linePaint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// HRV折线图绘制器（基于API数据）
class HrvLineChartPainter extends CustomPainter {
  final List<HeartRateInfo> data;
  final int selectedIndex;
  final double? dragLineX;
  final int maxValue;
  final int minValue;

  HrvLineChartPainter({
    required this.data,
    required this.selectedIndex,
    this.dragLineX,
    required this.maxValue,
    required this.minValue,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (data.isEmpty) return;

    // 过滤有效数据（value > 0）
    final validData = data.where((info) => info.value > 0).toList();
    if (validData.isEmpty) return;

    // 橙色折线画笔
    final linePaint = Paint()
      ..color = const Color(0xFFED5C2F)
      ..strokeWidth = 2.0
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;

    // 数据点画笔
    final pointPaint = Paint()
      ..color = const Color(0xFFED5C2F)
      ..style = PaintingStyle.fill;

    // 选中点画笔
    final selectedPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    // 计算HRV范围
    final range = maxValue - minValue;
    final displayMinValue = minValue - (range * 0.1).round();
    final displayMaxValue = maxValue + (range * 0.1).round();
    final displayRange = displayMaxValue - displayMinValue;

    // 计算缩放比例
    final scaleY = size.height / displayRange;

    // 创建曲线路径
    final linePath = Path();
    // 创建填充区域路径
    final fillPath = Path();
    double? lastX;

    // 收集所有有效数据点
    final List<Offset> points = [];
    for (int i = 0; i < data.length; i++) {
      final info = data[i];
      if (info.value <= 0) continue;

      // 解析时间（格式：HH:mm）
      final timeParts = info.code.split(':');
      final hour = int.parse(timeParts[0]);
      final minute = int.parse(timeParts[1]);
      final timeInHours = hour + minute / 60.0;

      // 计算坐标
      final x = (timeInHours / 24.0) * size.width;
      final y = size.height - (info.value - displayMinValue) * scaleY;
      
      points.add(Offset(x, y));
    }

    // 绘制平滑曲线
    if (points.isNotEmpty) {
      linePath.moveTo(points[0].dx, points[0].dy);
      fillPath.moveTo(points[0].dx, size.height);
      fillPath.lineTo(points[0].dx, points[0].dy);

      for (int i = 0; i < points.length - 1; i++) {
        final p0 = i > 0 ? points[i - 1] : points[i];
        final p1 = points[i];
        final p2 = points[i + 1];
        final p3 = i < points.length - 2 ? points[i + 2] : p2;

        // 计算控制点
        final cp1x = p1.dx + (p2.dx - p0.dx) / 6;
        final cp1y = p1.dy + (p2.dy - p0.dy) / 6;
        final cp2x = p2.dx - (p3.dx - p1.dx) / 6;
        final cp2y = p2.dy - (p3.dy - p1.dy) / 6;

        linePath.cubicTo(cp1x, cp1y, cp2x, cp2y, p2.dx, p2.dy);
        fillPath.cubicTo(cp1x, cp1y, cp2x, cp2y, p2.dx, p2.dy);
      }

      lastX = points.last.dx;
    }

    // 完成填充路径
    if (lastX != null) {
      fillPath.lineTo(lastX, size.height);
      fillPath.close();

      // 绘制渐变填充
      final fillPaint = Paint()
        ..shader = ui.Gradient.linear(
          Offset(0, 0),
          Offset(0, size.height),
          [
            const Color(0xFFED5C2F).withOpacity(0.4),
            const Color(0xFFED5C2F).withOpacity(0.2),
            const Color(0xFFED5C2F).withOpacity(0.1),
          ],
          [0.0, 0.5, 1.0],
        )
        ..style = PaintingStyle.fill;

      canvas.drawPath(fillPath, fillPaint);
    }

    // 绘制折线
    canvas.drawPath(linePath, linePaint);

    // 绘制拖动线
    final dragX = dragLineX;
    if (dragX != null && dragX > 0) {
      final dragLinePaint = Paint()
        ..color = Colors.red.withOpacity(0.5)
        ..strokeWidth = 1.0;
      canvas.drawLine(
        Offset(dragX, 0),
        Offset(dragX, size.height),
        dragLinePaint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// 心率变异性页面
/// 显示心率变异性数据、图表和相关信息
class HeartRateVariabilityView extends GetView<HeartRateVariabilityLogic> {
  const HeartRateVariabilityView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 固定的头部（标题 + 日周月切换）
            Obx(() => FixedHeaderWithTabs(
                  title: '心率变异性',
                  selectedIndex: _getSelectedIndex(),
                  onTabChanged: (index) {
                    switch (index) {
                      case 0:
                        controller.setTimeRange(TimeRange.day);
                        break;
                      case 1:
                        controller.setTimeRange(TimeRange.week);
                        break;
                      case 2:
                        controller.setTimeRange(TimeRange.month);
                        break;
                    }
                  },
                  actions: [
                    IconButton(
                      icon: const Icon(Icons.stacked_bar_chart,
                          color: Colors.white),
                      onPressed: () {
                        Get.toNamed('/manual_measure', arguments: {'type': 'hrv'});
                      },
                    ),
                    IconButton(
                      icon: const Icon(Icons.calendar_today,
                          color: Colors.white),
                      onPressed: controller.showCalendarPicker,
                    ),
                  ],
                )),
            // 可滚动的内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Stack(
                  children: [
                    // 顶部渐变背景
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      height: 240.h,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.topRight,
                            end: Alignment.bottomRight,
                            colors: ThemeManager.to.backgroundGradientColors,
                            stops: const [0.1, 0.3, 0.7, 1.0],
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(16.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(height: 20.h),
                          _buildHrvDisplay(),
                          SizedBox(height: 12.h),
                          _buildDateLine(),
                          SizedBox(height: 16.h),
                          _buildHrvLineChartCard(),
                          SizedBox(height: 16.h),
                          _buildManualMeasurementRecordsCard(), // 手动测量记录卡片（独立）
                          SizedBox(height: 16.h),
                          _buildHrvInfoCard(),
                          SizedBox(height: 40.h), // 底部留空
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取当前选中的索引
  int _getSelectedIndex() {
    switch (controller.currentTimeRange.value) {
      case TimeRange.day:
        return 0;
      case TimeRange.week:
        return 1;
      case TimeRange.month:
        return 2;
    }
  }



  /// 构建心率变异性显示
  Widget _buildHrvDisplay() {
    return Obx(() {
      // 优先使用API数据
      final hrvAverageData = controller.hrvAverageData.value;

      if (hrvAverageData != null) {
        // 使用API数据
        int displayHrv;

        if (controller.selectedTimeIndex.value != -1) {
          // 显示选中时间点的HRV
          final selectedIndex = controller.selectedTimeIndex.value;
          if (selectedIndex < hrvAverageData.automaticInfoVOS.length) {
            final selectedInfo = hrvAverageData.automaticInfoVOS[selectedIndex];
            if (selectedInfo.value > 0) {
              displayHrv = selectedInfo.value;
            } else {
              displayHrv = hrvAverageData.average;
            }
          } else {
            displayHrv = hrvAverageData.average;
          }
        } else {
          // 显示平均HRV
          displayHrv = hrvAverageData.average;
        }

        return Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  '$displayHrv',
                  style: TextStyle(
                    fontSize: 64.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 8.h),
                  child: Text(
                    ' 毫秒',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 8.h),
          ],
        );
      } else {
        return Container(
          height: 120.h,
          child: Center(
            child: Text(
              '数据加载中...',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[500],
              ),
            ),
          ),
        );
      }
    });
  }

  /// 构建日期行
  Widget _buildDateLine() {
    return Obx(() {
      final dateTitle = controller.getDateTitle();
      return Text(
        dateTitle,
        style: TextStyle(fontSize: 14.sp, color: Colors.grey[400]),
      );
    });
  }

  /// 构建心率变异性折线图卡片
  Widget _buildHrvLineChartCard() {
    return _buildSectionCard(
      title: '心率变异性趋势',
      child: _buildHrvLineChart(),
    );
  }

  /// 构建心率变异性折线图
  Widget _buildHrvLineChart() {
    return Obx(() {
      final hrvAverageData = controller.hrvAverageData.value;
      final timeRange = controller.currentTimeRange.value;

      // 根据时间范围显示不同的图表
      if (timeRange == TimeRange.day) {
        return _buildDayLineChart(hrvAverageData);
      } else {
        return _buildWeekMonthBarChart(hrvAverageData, timeRange);
      }
    });
  }

  /// 构建日视图折线图
  Widget _buildDayLineChart(HrvAverageData? hrvAverageData) {
    // 如果没有数据，显示空图表结构
    if (hrvAverageData == null) {
      return _buildEmptyDayChart();
    }

    final automaticInfoVOS = hrvAverageData.automaticInfoVOS;
    final validData = automaticInfoVOS.where((info) => info.value > 0).toList();

    // 如果没有有效数据，显示空图表结构
    if (validData.isEmpty) {
      return _buildEmptyDayChart();
    }

    final minHrv = hrvAverageData.minValue;
    final maxHrv = hrvAverageData.maxValue;

    return SizedBox(
      height: 280.h,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                  width: 8.w,
                  height: 8.w,
                  decoration: const BoxDecoration(
                      color: Color(0xFFED5C2F), shape: BoxShape.circle)),
              SizedBox(width: 4.w),
              Text('HRV数据',
                  style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            ],
          ),
          SizedBox(height: 12.h),
          Expanded(
            child: Builder(
              builder: (context) => GestureDetector(
                onTapUp: (details) {
                  final RenderBox box = context.findRenderObject() as RenderBox;
                  final localPosition =
                      box.globalToLocal(details.globalPosition);
                  controller.handleChartTapUp(
                      localPosition.dx, box.size.width / 24, 24);
                },
                onPanUpdate: (details) {
                  final RenderBox box = context.findRenderObject() as RenderBox;
                  final localPosition =
                      box.globalToLocal(details.globalPosition);
                  controller.handleChartPanUpdate(
                      localPosition.dx, box.size.width / 24, 24);
                },
                onPanEnd: (_) => controller.handleChartPanEnd(),
                child: CustomPaint(
                  painter: HrvLineChartPainter(
                    data: automaticInfoVOS,
                    selectedIndex: controller.selectedTimeIndex.value,
                    dragLineX: controller.dragLineX.value,
                    maxValue: maxHrv,
                    minValue: minHrv,
                  ),
                  child: Container(),
                ),
              ),
            ),
          ),
          SizedBox(height: 8.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: ['00:00', '06:00', '12:00', '18:00', '24:00']
                .map((label) => Text(label,
                    style: TextStyle(fontSize: 10.sp, color: Colors.grey[400])))
                .toList(),
          ),
          SizedBox(height: 16.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.05),
                    borderRadius: BorderRadius.circular(12.r)),
                child: Text('最低${minHrv}毫秒',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.05),
                    borderRadius: BorderRadius.circular(12.r)),
                child: Text('最高${maxHrv}毫秒',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
            ],
          ),
          SizedBox(height: 16.h),
          Obx(() => GestureDetector(
                onTap: () {
                  if (controller.ringController.isHrvMeasuring) {
                    controller.ringController.stopHrvMeasure();
                  } else {
                    controller.ringController.startHrvMeasure();
                  }
                },
                child: Container(
                  width: double.infinity,
                  height: 48.h,
                  decoration: BoxDecoration(
                      color: const Color(0xFFBEBEBE),
                      borderRadius: BorderRadius.circular(24.r)),
                  child: Center(
                    child: Text(
                      controller.ringController.isHrvMeasuring
                          ? '停止测量'
                          : '开始测量',
                      style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.black,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  /// 构建手动测量记录卡片（独立卡片）
  Widget _buildManualMeasurementRecordsCard() {
    return Obx(() {
      final hrvAverageData = controller.hrvAverageData.value;
      if (hrvAverageData == null || hrvAverageData.manualInfoVOS.isEmpty) {
        return const SizedBox.shrink();
      }

      final isExpanded = false.obs;

      return _buildSectionCard(
        title: '当天测量记录 (${hrvAverageData.manualInfoVOS.length})',
        child: Obx(() => Column(
          children: [
            GestureDetector(
              onTap: () => isExpanded.value = !isExpanded.value,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      isExpanded.value ? '收起' : '展开查看',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                    SizedBox(width: 4.w),
                    Icon(
                      isExpanded.value ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                      color: Colors.grey[400],
                      size: 20.sp,
                    ),
                  ],
                ),
              ),
            ),
            if (isExpanded.value) ...[
              SizedBox(height: 8.h),
              ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 200.h),
                child: SingleChildScrollView(
                  child: Column(
                    children: hrvAverageData.manualInfoVOS.map((record) {
                      return Container(
                        margin: EdgeInsets.only(bottom: 8.h),
                        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.05),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              record.code,
                              style: TextStyle(
                                fontSize: 13.sp,
                                color: Colors.grey[300],
                              ),
                            ),
                            Text(
                              '${record.value} ms',
                              style: TextStyle(
                                fontSize: 13.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ],
          ],
        )),
      );
    });
  }

  /// 构建周/月视图柱状图
  Widget _buildWeekMonthBarChart(HrvAverageData? d, TimeRange timeRange) {
    // 如果没有数据，显示空图表
    if (d == null) {
      return SizedBox(
        height: 200.h,
        child: Center(
            child: Text('暂无数据',
                style: TextStyle(fontSize: 14.sp, color: Colors.grey[500]))),
      );
    }

    final validData = d.automaticInfoVOS
        .where(
            (point) => (point.maxValue ?? 0) > 0 || (point.minValue ?? 0) > 0)
        .toList();

    if (validData.isEmpty) {
      return SizedBox(
        height: 200.h,
        child: Center(
            child: Text('暂无数据',
                style: TextStyle(fontSize: 14.sp, color: Colors.grey[500]))),
      );
    }

    return SizedBox(
      height: 300.h,
      child: Column(
        children: [
          if (d.dateStart != null && d.dateEnd != null)
            Padding(
              padding: EdgeInsets.only(bottom: 12.h),
              child: Text('${d.dateStart} - ${d.dateEnd}',
                  style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            ),
          Expanded(
            child: BarChart(
              BarChartData(
                alignment: BarChartAlignment.spaceAround,
                maxY: 150,
                minY: 0,
                barTouchData: BarTouchData(
                  enabled: true,
                  touchTooltipData: BarTouchTooltipData(
                    getTooltipColor: (group) => Colors.grey[800]!,
                    getTooltipItem: (group, groupIndex, rod, rodIndex) {
                      final point = validData[group.x.toInt()];
                      return BarTooltipItem(
                        '${point.code}\n最高: ${point.maxValue}ms\n最低: ${point.minValue}ms',
                        TextStyle(color: Colors.white, fontSize: 11.sp),
                      );
                    },
                  ),
                ),
                titlesData: FlTitlesData(
                  show: true,
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        final index = value.toInt();
                        if (index >= 0 && index < validData.length) {
                          final code = validData[index].code;
                          final label = timeRange == TimeRange.week
                              ? _getWeekdayLabel(code)
                              : code.split('/').last;
                          return Text(label,
                              style: TextStyle(
                                  color: Colors.grey[400], fontSize: 10.sp));
                        }
                        return const SizedBox.shrink();
                      },
                      reservedSize: 20.h,
                    ),
                  ),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: 30,
                      getTitlesWidget: (value, meta) {
                        return Text('${value.toInt()}',
                            style: TextStyle(
                                color: Colors.grey[400], fontSize: 10.sp));
                      },
                      reservedSize: 25.w,
                    ),
                  ),
                  topTitles:
                      AxisTitles(sideTitles: SideTitles(showTitles: false)),
                  rightTitles:
                      AxisTitles(sideTitles: SideTitles(showTitles: false)),
                ),
                gridData: FlGridData(
                  show: true,
                  drawVerticalLine: false,
                  horizontalInterval: 30,
                  getDrawingHorizontalLine: (value) {
                    return FlLine(
                        color: Colors.grey.withOpacity(0.2), strokeWidth: 1);
                  },
                ),
                borderData: FlBorderData(show: false),
                barGroups: List.generate(validData.length, (index) {
                  final point = validData[index];
                  return BarChartGroupData(
                    x: index,
                    barRods: [
                      BarChartRodData(
                        fromY: (point.minValue ?? 0).toDouble(),
                        toY: (point.maxValue ?? 0).toDouble(),
                        color: const Color(0xFFED5C2F),
                        width: 16.w,
                        borderRadius:
                            BorderRadius.vertical(top: Radius.circular(4.r)),
                      ),
                    ],
                  );
                }),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空的日视图图表
  Widget _buildEmptyDayChart() {
    return SizedBox(
      height: 280.h,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 8.w,
                height: 8.w,
                decoration: const BoxDecoration(
                  color: Color(0xFFED5C2F),
                  shape: BoxShape.circle,
                ),
              ),
              SizedBox(width: 4.w),
              Text(
                'HRV数据',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          Expanded(
            child: Center(
              child: Text(
                '暂无数据',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[500],
                ),
              ),
            ),
          ),
          SizedBox(height: 8.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: ['00:00', '06:00', '12:00', '18:00', '24:00']
                .map((label) => Text(label,
                    style: TextStyle(fontSize: 10.sp, color: Colors.grey[400])))
                .toList(),
          ),
          SizedBox(height: 16.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text('最低--毫秒',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text('最高--毫秒',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.w500)),
              ),
            ],
          ),
          SizedBox(height: 16.h),
          Obx(() => GestureDetector(
                onTap: () {
                  if (controller.ringController.isHrvMeasuring) {
                    controller.ringController.stopHrvMeasure();
                  } else {
                    controller.ringController.startHrvMeasure();
                  }
                },
                child: Container(
                  width: double.infinity,
                  height: 48.h,
                  decoration: BoxDecoration(
                    color: const Color(0xFFBEBEBE),
                    borderRadius: BorderRadius.circular(24.r),
                  ),
                  child: Center(
                    child: Text(
                      controller.ringController.isHrvMeasuring
                          ? '停止测量'
                          : '开始测量',
                      style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.black,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  /// 获取星期标签
  String _getWeekdayLabel(String code) {
    final parts = code.split('/');
    if (parts.length == 2) {
      final month = int.tryParse(parts[0]) ?? 0;
      final day = int.tryParse(parts[1]) ?? 0;
      if (month > 0 && day > 0) {
        final date = DateTime(DateTime.now().year, month, day);
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        return weekdays[date.weekday % 7];
      }
    }
    return code;
  }

  /// 构建心率变异性信息说明卡片
  Widget _buildHrvInfoCard() {
    return _buildSectionCard(
      title: '关于心率变异性数据',
      child: _buildHrvInfo(),
    );
  }

  /// 构建心率变异性信息说明
  Widget _buildHrvInfo() {
    return Text(
      '心率变异性(HRV)用于测量心跳间隔时间的差异。通过心率传感器测量到的心跳间隔之标准差来计算HRV。HRV适用于18岁以上的用户。如果每两次心跳间隔时间的差异不大,则HRV就比较低;反之,则HRV就比较高。HRV越高越好,代表有着更好的心血管性能和抗压承受能力。',
      style: TextStyle(
        fontSize: 13.sp,
        color: Colors.grey[400],
        height: 1.5,
      ),
    );
  }

  /// 通用分区卡片（参考睡眠页面样式）
  Widget _buildSectionCard({
    required String title,
    required Widget child,
    VoidCallback? onHelpTap,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xff282528),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
            child: Row(
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
                const Spacer(),
                if (onHelpTap != null)
                  GestureDetector(
                    onTap: onHelpTap,
                    child: Icon(
                      Icons.help_outline,
                      color: Colors.white.withOpacity(0.9),
                      size: 18.sp,
                    ),
                  ),
              ],
            ),
          ),
          const Divider(
            height: 1,
            thickness: 1,
            color: Color(0xff353235),
          ),
          Padding(
            padding: EdgeInsets.all(12.w),
            child: child,
          ),
        ],
      ),
    );
  }
}
